﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;

namespace TGIApp.Web
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }
        protected void Application_Error(object sender, EventArgs e)
        {
            System.Web.HttpContext context = HttpContext.Current;
            System.Exception lastError = Context.Server.GetLastError();

            log.ErrorFormat("Application Error: {0} \n Stack Trace: {1}", lastError.Message, lastError.StackTrace.ToString());
        }
        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();
            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
        protected void Application_AuthenticateRequest()
        {
            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    if (HttpContext.Current.User.Identity is FormsIdentity)
                    {
                        FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
                        FormsAuthenticationTicket ticket = (id.Ticket);
                        if (!FormsAuthentication.CookiesSupported)
                        {
                            //If cookie is not supported for forms authentication, then the
                            //authentication ticket is stored in the URL, which is encrypted.
                            //So, decrypt it
                            ticket = FormsAuthentication.Decrypt(id.Ticket.Name);
                        }
                        // Get the stored user-data, in this case, user roles
                        if (!string.IsNullOrEmpty(ticket.UserData))
                        {
                            string userData = ticket.UserData;
                            string[] roles = userData.Split(',');
                            //Roles were put in the UserData property in the authentication ticket
                            //while creating it
                            HttpContext.Current.User =
                              new System.Security.Principal.GenericPrincipal(id, roles);
                        }
                    }
                }
            }
        }
    }
}